<?php
/**
 * 聊天
 * User: Tsang
 * Date: 2017/12/22 10:41
 *
 */

namespace app\admin\Controller;
use app\api\service\AesEncrypt;
use think\Cache;

class Chat extends Common
{

    /**
     * 客服列表
     */
    public function index(){
        $list  = db('chat')->where(['type' => '2'])->paginate(20);
        $this->assign('list',$list);
        //判断是否为手机打开，是手机打开就直接跳转到客服页面
        if(!isMobile()){
            return $this->fetch();
        }else{
            return $this->fetch('phone_index');
        }
    }

    /*
    *编辑客服名称
    */
    public function edit_kefu_name(){

        $id = input('id');

        $about_result = db('chat')->where(array('id'=>$id))->field('nickname,userid')->find();

        if(request()->isPost()){
            $nickname = input('nickname');
            $chat_list = db('chat')->where(array('nickname'=>$nickname))->select();
            $data['nickname'] = $nickname;

            if(count($chat_list)>0)$this->error('该昵称已被使用');

            //修改百川聊天
            $result = (new \app\api\logic\Chat())->set_user($data,$about_result['userid']);

            if(array_key_exists('message',$result)){
                $this->error('修改失败');
            }

            if(isset($result['uid_fail'])){
                $this->error('修改失败');
            }

            $data['nickname'] = $nickname;
            db('chat')->where(array('id'=>$id))->update($data);
            $this->redirect(url('Chat/index'));
        }

        $this->assign('id',$id);
        $this->assign('about_result',$about_result);
        return $this->fetch();
    }

    /**
     * 添加客服
     */
    public function add(){
        if($this->request->isPost()){
            $nick = input('nickname/s');
            $result = (new \app\api\logic\Chat())->create_user($nick,'kefu'.TIMESTAMP,'123456','2',0);
            if(array_key_exists('message',$result)) $this->error($result['message']);
            $this->redirect(url('chat/index'));
        }
        return $this->fetch();
    }

    /**
    * 删除客服
    */
    public function del_kefu_name(){
        $id = input('id');

        db('chat')->where(array('id'=>$id))->delete();

        $this->redirect(url('chat/index'));
    }

    /**
     * 聊天
     */
    public function chat(){
        $this->assign('id',input('id/d'));
        $this->assign('touid',input('touid/d'));
        //判断是否为手机打开，是手机打开就直接跳转到客服页面
        if(!isMobile()){
            return $this->fetch();
        }else{
            return $this->fetch('phone_chat');
        }
    }

    /**
     * 聊天
     */
    public function mkit(){
        $m_chat = db('chat');
        $chat = $m_chat->where(['id' => input('id/d'),'type' => '2'])->find();
        if(!$chat) $this->error( '找不到聊天账号');
        $this->assign('uid',$chat['userid']);
        $this->assign('pwd',$chat['pwd']);
        $this->assign('appkey',config('openim.appkey'));
        $touid = input('touid/d');
        $data = [
            'timestamp'=>time(),
            'uid' => $chat['id'],
            'goods_id' => 0,
        ];
        if($touid > 0){
            $touser = $m_chat->where(['id' => $touid, 'type' => '1'])->find();
            if (!$touser) $this->error('找不到对方账号');
            $this->assign('touid', $touser['userid']);
            $data['to_uid'] = $touser['id'];
        }else{
            $this->assign('touid', '0');
        }
        $endata = (new AesEncrypt())->encrypt(json_encode($data));
        $this->assign('token',$endata);
        $goods_id = input('goods_id/d');
        if($goods_id > 0){
            $url = url('chat/chatGood',['id' => $goods_id]);
        }else{
            $url = '';
        }
        $this->assign('url',$url);
        return $this->fetch();
    }

    /**
     * 聊天列表
     */
    public function chatList(){
        $id = input('id/d');
        $res = (new \app\api\logic\Chat())->chatList($id);
        if(array_key_exists('message',$res)){
            echo json_encode(['code' => -1,'msg' => $res['message']]);
            exit;
        }
        echo json_encode($res);
    }


    /**
     * 阅读信息
     */
    public function readChat(){
        $uid = input('uid/d');
        $touid = input('touid/d');
        $result = (new \app\api\logic\Chat())->readChat($uid,$touid);
        if(array_key_exists('message',$result)) $this->error($result['message']);
        $this->success();
    }

    /**
     * 设置聊天缓存
     */
    public function setChatCache(){
        $data = input('data/s');
        if(empty($data)) $this->error('数据不能为空');
        $string = json_decode((new AesEncrypt())->decrypt($data));
        $result = (new \app\api\logic\Chat())->setChatCache($string->uid,$string->to_uid,$string->goods_id);
        if(array_key_exists('message',$result)) $this->error($result['message']);
        $this->success();
    }


    /**
     * 聊天商品
     */
    public function chatGood(){
        $id = input('id/d');
        $goods = db('goods')->where(['id' => $id])->find();
        if($goods){
            $goods_spec = db('goods_option_value')->field('max(price) as max_price,min(price) as min_price')->where(['goodsid' => $goods['id']])->find();
            if(empty($goods['image'])){
                if(!empty($goods['images'])){
                    $images = unserialize($goods['images']);
                    $goods['image'] = $images[0];
                }
            }
            if($goods_spec){
                $data = $goods_spec;
                $data['image'] = __ROOT__ . '/static/uploads/'.str_replace('\\',"/",$goods['image']);
                $data['title'] = $goods['name'];
                $data['id'] = $goods['id'];
            }else{
                $data = array();
            }
        }else{
            $data = array();
        }
        $this->assign('data',$data);
        return $this->fetch();
    }


    /**
     * 删除刷新
     */
    public function delRefresh(){
        $id = input('id/d');
        Cache::set('chat_refresh'.$id,0);
    }

    /**
    *   客服电话
    */
    public function update_phone(){
        $phone = input('phone');

        $about_result = db('about')->where(array('id'=>'1'))->field('tel')->find();

        if(request()->isPost()){

            $data['tel'] = $phone;
            db('about')->where(array('id'=>'1'))->update($data);
            $this->redirect(url('Chat/update_phone'));
            //$this->success("操作成功!",url('Chat/update_phone'));
        }


        $this->assign('about_result',$about_result);
        return $this->fetch();
    }

}